<template>
    <div>
         <page-header @toLastPage="toLastPage">
            <template v-slot:title>
                <div>
                    聊天成员
                    <span v-if="groupUserCount!==0">({{groupUserCount}})</span>
                </div>
            </template>
            <template v-slot:right >
                <van-button type="primary" size="small" hairline color="#09BF63" :disabled='disabled' @click="removeUser" >删除</van-button>
            </template>
        </page-header>
    <div class="header-search">
    <van-field
        v-model="search"
        left-icon="search"
        placeholder="搜索"
    />
        </div>
        <div class="content">
        <van-index-bar>
    <van-checkbox-group v-model="result" checked-color='#07C160'>
  <div v-for="(item,index) in newFriendsList" :key="index">
    <div>
      <van-index-anchor :index="item.index" />
<div v-for="(item1,index1) in item.information" :key="index1">
    <van-cell value="">
  <!-- 使用 title 插槽来自定义标题 -->
    <template #title >
        <van-checkbox :name='item1.userId'>
             <van-image
            width="1.5rem"
            height="1.5rem"
            radius=".2rem"
            fit="cover"
            lazy-load
            class="f-center"
            :src="item1.avatar"
            />
            <span class="name">{{item1.groupName}}</span>
        </van-checkbox>
    </template>
  </van-cell>
</div>
    </div>
  </div>
  </van-checkbox-group>
        </van-index-bar>
        </div>
    </div>
</template>
<script>
import pageHeader from '../common/pageHeader';
import {Meteor} from 'meteor/meteor';
import { friends,groupUser,image, messages,user } from '../../../api/collections/index';
var pinyin = require("pinyin");
export default {
      components:{
        pageHeader
    },
        data() {
        return {
            id:sessionStorage.getItem('user'),
            groupId:this.$route.params.id,
             // 索引栏
            indexList:['*', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'],
            newFriendsList:[],
            result:[],
            lastMsg:''
        }
    },
    meteor: {
    $subscribe: {
      'userInf': []
    },
    friendsList(){
       let inUser = groupUser.find({gid:this.groupId}).fetch()
        let newArr = []
       let index = 0
         inUser.forEach(e => {
             if(e.userId !== this.id){
                 const userInf = user.findOne({_id:e.userId})
            if(userInf){
            Meteor.call('image.find',userInf.avatarId,(err,res)=>{
             if(err){
               this.$toast(err.error)
             }
             else{
               e.avatar = res.base64
            let check = e.groupName
         let fristName = pinyin(check, { style: pinyin.STYLE_NORMAL, heteronym: true })[0][0].substring(0, 1).toUpperCase();
          //进行判断，给原始json数据添加新的键值对
          if (this.indexList.includes(fristName) == true) { 
           if(newArr.some((item,i) =>{if(item.index == fristName){index=i;return true}})){
             newArr[index].information.push(e)
           }
           else{
             let arr = []
             arr.push(e)
             newArr.push({index:fristName,information:arr})
           }
          } else {
           if(newArr.some((item,i) =>{if(item.index == '#'){index=i;return true}})){
             newArr[index].information.push(e)
           }
           else{
             let arr = []
             arr.push(e)
             newArr.push({index:'#',information:arr})
           }
          }
             }
           }) 
                 } 
             }  
        });
       return newArr
    },
},
computed:{
        disabled(){
            if(this.result.length>0)return false
            else return true
        },
      groupUserCount(){
        let count = 0
        if(this.newFriendsList.length>0){
          this.newFriendsList.forEach(e=>{
            count = e.information.length + count
          })
          return count
        }
        else{
          return 0
        }
    }
},
 watch:{
      friendsList(){
        if(this.friendsList.length>0){
          this.newFriendsList=[...this.friendsList]
          this.newFriendsList.sort((item1,item2)=>{
            let val1 = item1.index
            let val2 = item2.index
            if (val1 < val2) {
              return -1;
          } else if (val1 > val2) {
              return 1;
          } else {
              return 0;
          }   
          })
           this.showLoading = false
        }
        else{
            setTimeout(()=>{
                 this.showLoading = false
            },500)
        }
      }
 },
 methods:{
      toLastPage(){
            this.$router.go(-1)
        },
        removeUser(){
            this.$dialog.confirm({
            title: '删除群成员',
            message: '确定要将选中的群成员踢出群聊吗?',
            })
            .then(() => {
                this.result.forEach(e => {
                    Meteor.call('groupUser.deleteOne',{
                    gid:this.groupId,
                    uid:e
                },(err,res)=>{
                    if(err){
                        this.$toast(err)
                    }else{
                        Meteor.call('indexMsg.delete',{userId:e,otherId:this.groupId})
                        Meteor.call('message.removeGroupOne',{gid:this.groupId,uid:e})
                    }
                })
                })
                this.$toast.success('操作成功')
                this.$router.push('/home')
            })
            .catch(() => {
                // on cancel
            });
        }
 }
}
</script>
<style scoped>
    .header-search{
        position: fixed;
        top: 1.5rem;
        left: 0;
        right: 0;
        z-index: 999;
        box-shadow: 0 .05rem .05rem -.05rem #888;
    }
    .van-button{
    margin-top: .3rem;
    padding: .25rem .5rem;
    height: auto;
}
   .header-search .van-cell{
       padding:.3rem;
   }
   .content{
        margin-top: 3.1rem;
        margin-bottom: 3.2rem;
    }
      .bottom{
        padding:.5rem;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #f3f3f3;
    }
    .right{
        text-align: right;
    }
    .right .van-button--small{
        height: 1.2rem;
    }
    .name{
    display: inline-block;
    position: relative;
    top: -.5rem;
    font-size: .6rem;
    left: .4rem;
    }
</style>